import { useEffect, useState, Key } from 'react'
import { Button, Table, Form, Input, Card, message, Tooltip } from 'antd';
import { EditOutlined, DeleteOutlined } from "@ant-design/icons"
import { hospitalSetRequest, deleteOneRequest,batchDeleteRequest } from '@/api/hospital/hospitalSetRequest';
import type { hospitalSetRecordsType, hospitalSetItemType } from "@api/hospital/model/hospitalSetType"
import "./index.css"
import { useNavigate } from 'react-router-dom';

//定义表单内容的内型
interface fieldValueType {
  hosname?: string,
  hoscode?: string
}

export default function HospitalSet() {
  //编程式路由跳转
  const navigate = useNavigate()
  //定义请求医院列表
  const [effectList, setEffectList] = useState<hospitalSetRecordsType>([])
  //定义当前页码
  const [current, setCurrent] = useState(1)
  //定义每页条数
  const [pageSize, setPageSize] = useState(3)
  //定义总数据条数
  const [total, setTotal] = useState(0)
  //定义数据加载动画
  const [isLoading, setIsLoading] = useState(false)
  //定义搜索框内的值
  const [fieldValue, setFieldValue] = useState<fieldValueType>({})
  //定义只供重载页面所需的useState
  const [reRender, setReRender] = useState(true)
  //定义全选时批量删除的状态
  const [isSelect, setIsSelect] = useState(true)
  //定义批量删除请求的ids参数
  const [batchIds,setBatchIds] = useState<Key[]>([])


  useEffect(() => {
    //请求开始开启动画
    setIsLoading(true)
    const hospitalSet = async () => {
      const result = await hospitalSetRequest({
        page: current,
        limit: pageSize,
        ...fieldValue
      })
      //设置初始列表
      setEffectList(result.records)

      //请求结束后设置总条数
      setTotal(result.total)
      //请求结束后关闭动画
      setIsLoading(false)
    }

    hospitalSet()
    return
  }, [current, pageSize, fieldValue, reRender])



  //事件回调函数
  //页码改变回调
  const pageChangeHandle = (current: number, pageSize: number) => {
    setCurrent(current)
    setPageSize(pageSize)
  }
  //查询表单提交回调
  const searchHospitalHandle = (FieldValue: fieldValueType) => {
    //参数是表单的值
    setFieldValue(FieldValue)
  }
  //点击添加医院跳转路由回调
  const navigatorHandle = () => {
    navigate('/syt/hospital/addHospital')
  }
  //根据id点击删除单个数据
  const deleteOneHandle = (id: number) => {
    return async () => {
      await deleteOneRequest(id)
      //删除后重载页面
      setReRender(!reRender)
      //全局弹窗
      message.success('删除成功')
    }
  }
  // 批量删除请求回调
  const batchDeleteHandle = async() => { 
  await  batchDeleteRequest(batchIds)
  //删除后重载页面
  setReRender(!reRender)
  //全局弹窗
  
  message.success('批量删除成功')

  setIsSelect(true)
  }
  
  const columns = [
    {
      title: '序号',
      width: 30,
      dataIndex: 'name',
      key: 'name',
      render: (_: any, __: any, index: number) => index + 1,
    },
    {
      title: '医院名称',
      dataIndex: 'hosname',
      key: 'name',

    },
    {
      title: '医院编号',
      dataIndex: 'hoscode',
      key: 'name',

    },
    {
      title: 'api基础路径',
      dataIndex: 'apiUrl',
      key: 'name',

    },
    {
      title: '签名',
      dataIndex: 'signKey',
      key: 'name',

    },
    {
      title: '联系人姓名',
      dataIndex: 'contactsName',
      key: 'name',

    },
    {
      title: '联系人电话',
      dataIndex: 'contactsPhone',
      key: 'name',

    },
    {
      title: '操作',
      fixed: "right" as "right",
      render(_: any, data: hospitalSetItemType) {
        //render接收三个参数
        const { id } = data
        return (
          <div>
            <Tooltip title="修改">
              <Button
                type='primary'
                icon={<EditOutlined />}
                className="mr"
                onClick={() => { navigate(`/syt/hospital/updataHospital/${id}`) }}
              ></Button>
            </Tooltip>
            <Tooltip title="删除">
              <Button
                type='primary'
                danger
                icon={<DeleteOutlined />}
                onClick={deleteOneHandle(id)}
              ></Button>
            </Tooltip>
          </div >
        )
      }
    },
  ];


  return (
    <div className='outer'>
      <Card>
        <Form
          name="basic"
          wrapperCol={{ span: 24 }}
          layout='inline'
          onFinish={searchHospitalHandle}
        >
          <Form.Item
            name="hosname"
          >
            <Input placeholder="医院名称" />
          </Form.Item>
          <Form.Item
            name="hoscode"
          >
            <Input placeholder="医院编号" />
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
            <Button type="primary" htmlType="submit">
              查询
            </Button>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
            <Button type="default" htmlType="reset">
              清空
            </Button>
          </Form.Item>
        </Form>
        <div className='mt'>
          <Button type='primary' onClick={navigatorHandle} className='mr'>添加</Button>
          <Button type='primary' danger disabled={isSelect} onClick={batchDeleteHandle}>批量删除</Button>
        </div>
        <Table
          className="mt"
          columns={columns}
          dataSource={effectList}
          rowKey="id"
          bordered
          scroll={{ x: 1000 }}
          loading={isLoading}
          pagination={{
            current,
            pageSize,
            total,
            pageSizeOptions: [2, 3, 4, 5],
            showSizeChanger: true,
            showTotal(total) {
              return `共${total}条数据`
            },
            onChange: pageChangeHandle
          }}
          rowSelection={{
            onChange(ids: Key[]) {
              //当ids长度不为0时,批量删除状态改变
              setIsSelect(!ids.length)
              //保存ids
              setBatchIds(ids)
            }
          }}
        />;
      </Card>
    </div>
  )
}
